<template>
  <div class="appcontainer personal-group">
    <el-dialog
      :model-value="open"
      :title="options.title"
      @close="cancel"
      :width="options.width"
      class="configModal"
    >
      <el-scrollbar height="520px">
        <template v-for="item in groupList" :key="item.id">
          <div class="businessBox">
            <el-card
              :class="[
                'card-box',
                `${options.isEdit ? '' : 'cursor-pointer'}`,
                !options.isEdit ? selectClass(item) : ''
              ]"
              @click="rowClick(item)"
            >
              <div
                v-if="!options.isEdit"
                class="absolute top-10px left-10px cursor-pointer"
              >
                <span :class="[rowClass(item)]"></span>
              </div>
              <div
                v-if="options.isEdit"
                class="absolute top-10px right-10px cursor-pointer"
              >
                <el-dropdown>
                  <span class="el-dropdown-link">
                    <el-icon><More /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="editGroupName(item)"
                        >编辑分组名称</el-dropdown-item
                      >
                      <el-dropdown-item @click="editLeader(item)"
                        >编辑人员</el-dropdown-item
                      >
                      <el-dropdown-item @click="deleteGroup(item)"
                        >删除分组</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="mt-15px mb-20px moreHidden">
                分组名称：{{ item.businessName }}
              </div>
              <el-tooltip
                popper-class="tip-box"
                effect="dark"
                :disabled="showTip"
                :content="
                  item.businessLeaderName && item.businessLeaderName.length
                    ? item.businessLeaderName.toString()
                    : ''
                "
                placement="bottom"
              >
                <div class="moreHidden" @mouseenter="spanMouseenter($event)">
                  分组人员：{{
                    item.businessLeaderName && item.businessLeaderName.length
                      ? item.businessLeaderName.toString()
                      : ''
                  }}
                </div></el-tooltip
              >
            </el-card>
          </div>
        </template>
      </el-scrollbar>
      <template #footer>
        <div>
          <el-button v-if="options.isEdit" type="primary" @click="addGroup"
            >新增分组</el-button
          >
          <el-button v-if="!options.isEdit" type="primary" @click="confirmBtn"
            >确认</el-button
          >
          <el-button @click="cancel">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改分组名称 -->
    <el-dialog
      :title="dialogTitle"
      v-model="showEditName"
      width="500"
      @close="editCancel"
    >
      <el-form :model="form" label-width="100" ref="editNameForm">
        <el-form-item
          label="分组名称"
          prop="businessName"
          :rules="[
            { required: true, message: '请输入分组名称', triggle: 'blur' }
          ]"
        >
          <el-input v-model="form.businessName" style="width: 350px"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="editConfirm">确认</el-button>
          <el-button @click="editCancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改分组人员 -->
    <SelectDialog
      v-if="dialogParam.isDialog"
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="closeFn"
    ></SelectDialog>
  </div>
</template>

<script setup name="PersonalGroup">
import { listGroup, saveGroup, delGroup } from '@/api/system/notice'
import { useComputed, strToArr } from '@/utils/commo'
import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance()
const props = defineProps({
  open: {
    type: Boolean,
    require: true,
    default: false
  },
  groupConfig: {
    type: [Array, Object],
    default: () => {
      return {
        apiParams: {},
        defaultSelect: [], //{businessId:1,businessName:'张三'}
        options: {}
      }
    }
  }
})
const queryParams = ref({})
const groupList = ref([])
const selectArr = ref([])
const options = ref({
  multiple: true,
  isEdit: false, //是否可编辑分组
  title: '人员分组',
  width: '800'
})
// watch(
//   () => props.groupConfig,
//   () => {
//     if (props.groupConfig.queryParams) {
//       queryParams.value = {
//         ...queryParams.value,
//         ...props.groupConfig.apiParams
//       }
//     }
//     if (props.groupConfig.options) {
//       options.value = {
//         ...options.value,
//         ...props.groupConfig.options
//       }
//     }
//     if (
//       props.groupConfig.defaultSelect &&
//       props.groupConfig.defaultSelect.length > 0
//     ) {
//       selectArr.value = props.groupConfig.defaultSelect.map(item => {
//         if (typeof item != 'object') {
//           return { businessId: item }
//         } else {
//           return item
//         }
//       })
//     }

//     getList()
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )
watch(
  () => props.open,
  () => {
    if (props.open) {
      if (props.groupConfig.queryParams) {
        queryParams.value = {
          ...queryParams.value,
          ...props.groupConfig.apiParams
        }
      }
      if (props.groupConfig.options) {
        options.value = {
          ...options.value,
          ...props.groupConfig.options
        }
      }
      // if (
      //   props.groupConfig.defaultSelect &&
      //   props.groupConfig.defaultSelect.length > 0
      // ) {
      //   selectArr.value = props.groupConfig.defaultSelect.map(item => {
      //     if (typeof item != 'object') {
      //       return { businessId: item }
      //     } else {
      //       return item
      //     }
      //   })
      // }

      getList()
    }
  },
  {
    deep: true,
    immediate: true
  }
)

const emit = defineEmits(['update:open', 'ok'])

// 单击行
function rowClick(row, column, event) {
  // 根据id判断当前点击的是否被选中
  if (options.isEdit) return
  const selected = selectArr.value.some(
    item => item.businessId == row.businessId
  )
  if (!selected && options.value.multiple) {
    // 选择
    selectArr.value.push(row)
  } else if (!selected && !options.value.multiple) {
    // 选择
    selectArr.value = [row]
  } else {
    // 取消
    let finalArr = selectArr.value.filter(item => {
      return item.businessId != row.businessId
    })
    // 取消后剩余选中的
    selectArr.value = finalArr
  }
}

// 选中行样式
// const rowClass = computed(() => {
//   return function (row) {
//     let select = selectArr.value.some(e => e.businessId == row.businessId)
//     return select
//       ? 'i-ic-baseline-check-box text-blue-500'
//       : 'i-ic-baseline-check-box-outline-blank'
//   }
// })
const rowClass = row => {
  let select = selectArr.value.some(e => e.businessId == row.businessId)
  return select
    ? 'i-ic-baseline-check-box text-blue-500'
    : 'i-ic-baseline-check-box-outline-blank'
}
const selectClass = row => {
  let select = selectArr.value.some(e => e.businessId == row.businessId)
  return select ? 'border border-indigo-600 border-solid' : ''
}

// 初始化选中
const initSelect = () => {
  let defaultSelect = strToArr(props.groupConfig?.defaultSelect)
  if (
    defaultSelect &&
    defaultSelect.length > 0 &&
    groupList.value &&
    groupList.value.length > 0
  ) {
    selectArr.value = defaultSelect.map(item => {
      let value
      for (const e of groupList.value) {
        if (item == e.businessId || item?.businessId == e.businessId) {
          value = e
          break
        }
      }
      value = typeof value == 'object' ? value : { businessId: item }
      return value
    })
  }
}

function getList() {
  listGroup(queryParams.value).then(res => {
    groupList.value = res.data
    initSelect()
  })
}

const dialogTitle = ref('')
function editGroupName(item) {
  dialogTitle.value = '修改分组名称'
  showEditName.value = true
  editGroup.value = { ...item }
  form.value = { ...item }
}
function editLeader(item) {
  console.log(item, 1)
  editGroup.value = item
  dialogParam.value.isDialog = true
  dialogParam.value.defaultCheckedKeys =
    item.businessLeaderId && item.businessLeaderId.length
      ? item.businessLeaderId
      : []
}
function deleteGroup(item) {
  proxy.$modal.confirm('是否确认删除该分组').then(() => {
    delGroup({ ids: item.businessId }).then(() => {
      proxy.$modal.msgSuccess('删除成功')
      getList()
    })
  })
}

const form = ref({})
const editGroup = ref({})
// 修改分组名称
const showEditName = ref(false)

function editConfirm() {
  proxy.$refs.editNameForm.validate(valid => {
    if (valid) {
      const params = {
        businessId: editGroup.value.businessId,
        ...form.value
      }
      if (dialogTitle.value === '新增分组') {
        delete params.businessId
      }
      saveGroup(params).then(() => {
        editCancel()
        proxy.$modal.msgSuccess('修改成功')
        getList()
      })
    }
  })
}
function editCancel() {
  showEditName.value = false
  form.value = {}
}

// 修改分组人员
const dialogParam = ref({
  isDialog: false, //是否弹出框
  title: '修改分组人员', //弹出框的标题
  multiple: true, //是否多选
  dataType: 'person',
  //   data: [], // tree的数据 如果是人员的数据的话，传dataType:'person'，data 数据可以不用

  apiParams: {
    disabled: 'false',
    deptId:
      useUserStore().user['orgId'] == '484'
        ? undefined
        : useUserStore().user['orgId']
  },
  nodeKey: 'uuid', //数据唯一值，默认是id
  checkStrictly: false, //是否遵循父子不互相关联的做法，默认为 false
  defaultCheckedKeys: []
})

/**
 *  dialog确定返回数据
 *  判断是否更新人员
 *  调用接口更新分组人员信息
 */
function selectDialogData(val) {
  const personId = val.defaultCheckedKeys.map((v, i) => {
    return {
      value: v.replace('U', ''),
      label: val.labelData[i]
    }
  })
  const defaultCheckedKeys = val.defaultCheckedKeys.map(v => v.replace('U', ''))
  /**
   * 判断是否需要更新
   * 分组人员为空
   * 分组人员id与之前的不一致
   */
  const needUpdate =
    !editGroup.value.businessLeaderId ||
    !editGroup.value.businessLeaderId.length ||
    editGroup.value.businessLeaderId.length !== defaultCheckedKeys.length ||
    editGroup.value.businessLeaderId.some(
      v => !defaultCheckedKeys.includes(v)
    ) ||
    defaultCheckedKeys.some(v => !editGroup.value.businessLeaderId.includes(v))

  if (needUpdate) {
    saveGroup({
      businessId: editGroup.value.businessId,
      businessName: editGroup.value.businessName,
      businessLeaderId: defaultCheckedKeys,
      businessLeaderName: personId.map(v => v.label)
    }).then(() => {
      proxy.$modal.msgSuccess('修改成功')
      getList()
    })
  }
}

function closeFn() {
  dialogParam.value.isDialog = false
}

function addGroup() {
  dialogTitle.value = '新增分组'
  showEditName.value = true
}

// 确认选择
const confirmBtn = () => {
  if (selectArr.value.length == 0) return proxy.$modal.msgError('请选择分组')

  emit('ok', { value: selectArr.value, options: options.value })
  cancel()
}

const showTip = ref(false)
function spanMouseenter(ev) {
  if (ev.target.clientHeight < ev.target.scrollHeight) {
    showTip.value = false
  } else {
    showTip.value = true
  }
}

function cancel() {
  emit('update:open')
}
</script>

<style scoped lang="scss">
.personal-group {
  .businessBox {
    position: relative;
    @apply p-x-3;
    .card-box {
      height: 150px;
      position: relative;
    }
  }
  .moreHidden {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2; // 控制多行的行数
    -webkit-box-orient: vertical;
  }
}

::v-deep(.configModal .el-dialog__body) {
  padding-right: 0;
  padding-left: 0;
}
::v-deep(.el-scrollbar__view) {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  flex-wrap: wrap;
  // justify-content: space-between;
  padding: 0 30px;
  grid-row-gap: 20px;
}
</style>
<style>
.tip-box {
  max-width: 500px;
}
</style>
